import { Component, OnInit } from "@angular/core";
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from "../../shared/smartadmin.config";
import { stat } from "fs";

declare var $: any;
declare var echarts: any;
@Component({
	selector: "sa-project-daily",
	templateUrl: "./project-daily.component.html",
})
export class ProjectDailyComponent implements OnInit {
	tableData: any = []; //table数据
	startTime: string = ""; //开始时间
	endTime: string = ""; //结束时间
	selectedCompanyId: string = ""; //公司ID
	selectedCompanyName: string = ""; //公司名称
	carNumber: string = "";
	dataSort: string = "1";
	sortBy: string = "0";
	sortType: string = "1";
	quantityType: string = "";
	userName: string = ""; //上传人
	constructor(
		private jsonApiService: JsonApiService,
		private router: Router,
		private activatedRoute: ActivatedRoute
	) {
		activatedRoute.queryParams.subscribe((queryParams) => {
			//			this.curPage = queryParams.nowPage == undefined? 1:queryParams.nowPage;
		});
	}
	ngOnInit() {
		this.initDate().then(() => {
			this.load();
		});
	}
	ngOnDestroy() {
		document.onclick = null;
	}

	initDate() {
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import(
				"assets/js/datepicker/js/bootstrap-datetimepicker.min.js"
			).then(() => {
				System.import(
					"assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js"
				).then(() => {
					$("#datetimepicker1")
						.datetimepicker({
							//时间插件
							format: "yyyy-mm-dd",
							language: "zh-CN",
							autoclose: true,
							minView: 2,
						})
						.on("changeDate", function (e) {
							var date = e.date;
							var time = common.getTimeMmss(date);
							// $("#datetimepicker2").datetimepicker("setStartDate", time);
							var timeToDay = new Date()
								.toLocaleDateString()
								.replace("/", "-");
							$("#datetimepicker1").datetimepicker(
								"setEndDate",
								$("#datetimepicker2").val() + " 23:59:59"
							);
							$("#datetimepicker2").datetimepicker(
								"setStartDate",
								time
							);
							$("#datetimepicker2").datetimepicker(
								"setEndDate",
								timeToDay
							);
						});
					$("#datetimepicker2")
						.datetimepicker({
							//时间插件
							format: "yyyy-mm-dd",
							language: "zh-CN",
							autoclose: true,
							minView: 2,
						})
						.on("changeDate", function (e) {
							var date = e.date;
							var time = common.getTimeMmss(date);
							// $("#datetimepicker1").datetimepicker("setEndDate", time);
							var timeToDay = new Date()
								.toLocaleDateString()
								.replace("/", "-");
							$("#datetimepicker1").datetimepicker(
								"setEndDate",
								time
							);
							$("#datetimepicker2").datetimepicker(
								"setEndDate",
								timeToDay
							);
							$("#datetimepicker2").datetimepicker(
								"setStartDate",
								$("#datetimepicker1").val() + " 00:00:00"
							);
						});
					let nowDate = common.getNowTime().split(" ")[0];
					$("#datetimepicker1").val(nowDate);
					$("#datetimepicker2").val(nowDate);
					resolve();
				});
			});
		});
	}
	//清除所选时间
	del_date() {
		this.startTime = "";
		this.endTime = "";
		$("#datetimepicker1").val("").change();
		$("#datetimepicker2").val("").change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	// 排序change
	sortChange() {
		switch (this.dataSort) {
			case "1":
				this.sortBy = "0";
				this.sortType = "1";
				break;
			case "2":
				this.sortBy = "0";
				this.sortType = "0";
				break;
			case "3":
				this.sortBy = "1";
				this.sortType = "1";
				break;
			case "4":
				this.sortBy = "1";
				this.sortType = "0";
				break;
			case "5":
				this.sortBy = "2";
				this.sortType = "1";
				break;
			case "6":
				this.sortBy = "2";
				this.sortType = "0";
				break;
			default:
				this.sortBy = "0";
				this.sortType = "1";
				this.dataSort = "1";
				break;
		}
	}
	// 数据导出
	exportData() {
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		if (!this.startTime || !this.endTime) {
			this.jsonApiService.message("时间范围不能为空");
			return;
		}
		const param = {
			companyId: this.selectedCompanyId,
			startTime: this.startTime + " 00:00:00",
			endTime: this.endTime + " 23:59:59",
			sortBy: this.sortBy,
			sortType: this.sortType,
			quantityType: this.quantityType,
			userName: this.userName,
		};
		common.exprotDataFile(param, 'param', config.BaseURL + 'projectDaily/exportProjectDailyData.html')
	}
	//表格搜索
	table_search() {
		this.load();
	}
	//刷新
	refresh() {
		this.load();
	}
	//初始化加载list数据
	load() {
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		if (!this.startTime || !this.endTime) {
			this.jsonApiService.message("时间范围不能为空");
			return;
		}
		let tableSearch = {
			parameters: {
				companyId: this.selectedCompanyId,
				startTime: this.startTime + " 00:00:00",
				endTime: this.endTime + " 23:59:59",
				sortBy: this.sortBy,
				sortType: this.sortType,
				quantityType: this.quantityType,
				userName: this.userName,
			},
		};
		let reqdata = "gridPager=" + JSON.stringify(tableSearch);
		this.jsonApiService
			.http("projectDaily/list.html", reqdata)
			.subscribe((data) => {
				if (data.success) {
					var result = data.data;
					// 遍历处理子节点
					this.tlist = [];
					this.initTableData(result);
					for (let item of this.tlist) {
						item.installedRatio = item.expectedNum? ((item.totalNum * 100) / item.expectedNum).toFixed(2) + "%": "";
						item.alertFlag = false;
						if (item.fieldEquipment < 5) {
							item.alertFlag = true;
						}
						if (item.peopleNumber) {
							if (item.installedNum / item.peopleNumber < 3) {
								item.alertFlag = true;
							}
						}
						if(!item.childNode||item.childNode.length==0){
							item.canEdit = true;
						}else{
							item.canEdit = false;
						}
					}
					this.tableData = this.tlist;
				}
			});
	}
	// 标记等级的
	level = 0;
	// 最后遍历形成的平级数组
	tlist = [];
	// 父级的id
	parentId :number = 0;
	// 递归处理表单数据
	initTableData(result) {
		for (let index = 0; index < result.length; index++) {
			const item = result[index];
			item.noShow = false;
			this.tlist.push(item);
			if (item.isTop) {
				this.level = 0;
				item.parentId = 0;
			}else{
				item.parentId = this.parentId;
			}
			item.level = this.level;
			// 这里是个数组
			if (item.childNode&&item.childNode.length>0) {
				this.parentId = item.id;
				item.isShowChild = true;
				this.level += 1;
				this.initTableData(item.childNode);
			}
		}
	}
	// 删除
	delRow(row) {
		this.jsonApiService
			.confirm_message("此操作将永久删除数据,确认要删除?")
			.then(() => {
				let reqdata = "id=" + row.id;
				this.jsonApiService
					.http("projectDaily/deletedById.html", reqdata)
					.subscribe((data) => {
						this.jsonApiService.message(data.message);
						if (data.success) {
							this.load();
						}
					});
			});
	}
	// 编辑表单数据
	projectDailyFrom: any = {
		id: "",
		companyName: "",
		companyId: "",
		installedNum: "",
		repairsNum: "",
		fieldEquipment: "",
		onlineNumber: "",
		weather: "",
		totalNum: "",
		expectedNum: "",
		peopleNumber: "",
		installer: "",
		maintenanceStaff: "",
		remark: "",
		projectName: "",
		area: "",
		userName: "",
		isTop:0,
	};
	// 编辑
	editRow(row) {
		$("#projectDailyModal").modal("show");
		for (let key in this.projectDailyFrom) {
			this.projectDailyFrom[key] = row[key];
		}
	}
	// 编辑取消
	projectDailyCancel() {
		$("#projectDailyModal").modal("hide");
	}
	// 编辑提交
	projectDailySubmit() {
		this.jsonApiService
			.http_obj("projectDaily/update.html", this.projectDailyFrom)
			.subscribe((data) => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					this.projectDailyCancel();
				}
			});
	}
	itemPageForm: any = {
		title: "代维人员",
		key: "maintenanceStaff",
	};
	// 单项编辑
	editItemPage(title, key, row) {
		for (let key in this.projectDailyFrom) {
			this.projectDailyFrom[key] = row[key];
		}
		$("#itemModal").modal("show");
		this.itemPageForm.title = title;
		this.itemPageForm.key = key;
	}
	// 单项编辑取消
	itemModalClose() {
		$("#itemModal").modal("hide");
	}
	// 单项数据提交
	itemModalSubmit() {
		if (
			this.itemPageForm.key == "fieldEquipment" ||
			this.itemPageForm.key == "peopleNumber" ||
			this.itemPageForm.key == "onlineNumber"
		) {
			if (isNaN(this.projectDailyFrom[this.itemPageForm.key])) {
				this.jsonApiService.message("请输入数字格式");
				return;
			}
		}
		this.jsonApiService
			.http_obj("projectDaily/update.html", this.projectDailyFrom)
			.subscribe((data) => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					this.itemModalClose();
				}
			});
	}
	//公司选中回调
	companySelected(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	// 页面跳转
	jumpPage(Url, row) {
		row.startTime = this.startTime + " 00:00:00";
		row.endTime = this.endTime + " 23:59:59";
		let BaseURL =
			window.location.protocol +
			"//" +
			window.location.hostname +
			":" +
			window.location.port;
		common.setCookie("jumpTo" + Url, JSON.stringify(row));
		window.open(BaseURL + "#" + Url);
	}
	// 展开单行
	openTr(parent) {
		parent.isShowChild = !parent.isShowChild
		for (let index = 0; index < this.tableData.length; index++) {
			const element = this.tableData[index];
			// 不仅id要一样  date也要一样
			if((element.parentId == parent.id)&&(element.date==parent.date)){
				// noShow 不展示 所以要和父组件的isShowChild取反
				element.noShow = !parent.isShowChild
				// 为了适配多级
				if(element.childNode&&element.childNode.length>0){
					this.shrinkData(element.childNode,!parent.isShowChild)
				}
			}
		}
	}
	// 递归进行收缩或展开  适配多级
	shrinkData(data,state){
		for (let idx = 0; idx < data.length; idx++) {
			const element = data[idx];
			// 只更改子集的
			if(!element.isTop){
				element.noShow = state;
			}
			if(element.childNode&&element.childNode.length!=0){ 
				element.isShowChild = !state;
				this.shrinkData(element.childNode,state)
			}
		}
	}
	isAllOpen:boolean = true;
	btnText:string = '一键收缩';
	// 一键展开一键缩放
	oneKeyChange(){
		if(this.isAllOpen){
			this.shrinkData(this.tableData,true)
			this.isAllOpen = false;
			this.btnText = '一键展开'
		}else{
			this.shrinkData(this.tableData,false)
			this.isAllOpen = true;
			this.btnText = '一键收缩'
		}
	}
}
